import router from '@/router'
import { osTenantId } from '@/config/app'
import { local, session } from '@/utils/jcore/storage'
import { MessageBox, Message } from 'element-ui'
import { encrypt } from '@/utils/aes.js'
/**全局请求默认配置 */
export const DefaultConfig = {
  baseURL: '/',
  timeout: 8000
}
/**默认控制配置 */
export const DefaultOptions = {
  tip: true,
  getCode: (res) => res.code,
  getResData: (res) => res.result || res.data
}

let resetLogin = false
/**创建配置 */
function createApiControlConfig(options) {
  options = Object.assign({}, DefaultOptions, options)
  const { tip, getCode, getResData } = options
  return {
    // 请求之前
    requestBefore: function (config) {
    console.log(config.data);
      // config.data={a:encrypt(JSON.stringify(config.data))}
      if (
        config.method == 'post' &&
        config.headers['content-type'] != 'application/x-www-form-urlencoded' &&
        config.headers['content-type'] != 'multipart/form-data;'
      ) {
        config.data = { a: encrypt(JSON.stringify(config.data)) }
      }
      /**
       * 添加请求token
       */
      const user = local.get('userInfo')
      const token = {
        osTenantId,
        'User-Identity': user ? user.sysOrganizeUserId : '',
        'X-Authorization': session.get('token') || ''
      }
      // 为请求添加统一参数
      if (config.headers) {
        config.headers = Object.assign({}, config.headers, token)
      } else {
        config.headers = token
      }
      return config
    },
    // 请求错误
    requestError: function (error) {
      Message.error('请求异常')
      return Promise.reject(error)
    },
    // 响应数据
    responseBefore: function ({ data ,msg}) {
      if (data.code != '1') {
        Message.error(msg || '服务器内部错误')
        return Promise.reject(data)
      }
      const res = data
      const code = getCode(res)
      // 判断 code 然后返回
      if (code == '1') {
      
        if (res?.msg) {
          Message.success(res.msg)
        }
        return getResData(res)
      } else if (code == '10000') {
        if (resetLogin) {
          console.log('已重定向')
          return
        }
        resetLogin = true

        // 清除缓存
        local.remove('token')
        local.remove('dutylist')
        local.remove('authorityList')

        MessageBox.confirm('登录失效请重新登录', '提示', {
          confirmButtonText: '确定',
          showCancelButton: false,
          showClose: false,
          type: 'warning',
          center: true
        }).then(() => {
          resetLogin = false
          if (router.currentRoute.path != '/login') {
            router.replace('/login')
          }
        })
        return Promise.reject(res)
      } else {
        let message = res.message || res.msg || '请求失败'
        
          Message.error(message)
       
        return Promise.reject(message)
      }
    },
    // 响应错误
    responseError: function (error) {
      let errorMsg = '服务器异常'
      if (error?.response?.status == 404) {
        errorMsg = '请求地址不存在'
      }
      Message.error(errorMsg)
      return Promise.reject(error)
    }
  }
}

/**全局请求流程控制参数 */
export const ApiControlConfig = createApiControlConfig()
